package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-master1/cache"
	"order-master1/models"
	"strconv"
	"time"
)

/*
SELECT
  orders.id AS OrdersId,
  goods.goods_name AS GoodsName,
  goods.price AS Price,
  orders.num AS Num
FROM
  orders
  LEFT JOIN goods ON orders.gid = goods.id
*/

func ListOrder(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var goods_order []models.GoodsOrder

	redis_key := "order_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.id AS OrdersId",
				"goods.goods_name AS GoodsName",
				"goods.price AS Price",
				"orders.num AS Num",
			).Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Offset(offset).
			Limit(size).
			Find(&goods_order)
		jsonData, _ := json.Marshal(goods_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goods_order)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  goods_order,
		"total": total,
	})
	return
}

func FindOrder(c *gin.Context) {
	id := c.Query("id")

	var goods_order models.GoodsOrder

	redis_key := "order_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.id AS OrdersId",
				"goods.goods_name AS GoodsName",
				"goods.price AS Price",
				"orders.num AS Num",
			).Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Where("orders.id=?", id).
			Find(&goods_order)
		jsonData, _ := json.Marshal(goods_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goods_order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": goods_order,
	})
	return
}
